package com.hy.main.api;

import com.itextpdf.text.pdf.BaseFont;

import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xhtmlrenderer.pdf.ITextRenderer;

import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Nick Liu
 * @date 2023/3/1
 */
@Slf4j
@RestController
@RequiredArgsConstructor
public class PdfGenerationController {

	private final Configuration configuration;

	@RequestMapping("/pdf/preview")
	public ResponseEntity<byte[]> downloadPdfWithFixedHeaderAndFooter() {
		Map<String, Object> map = new HashMap<>();
		map.put("dealerName","测试门店名称");

		ByteArrayOutputStream os = new ByteArrayOutputStream();
		try {
			// 不建议直接创建Template实例，开销比较大，可以直接通过Configuration实例获取，有缓存机制
			Template template = configuration.getTemplate("personalAccountProof.ftl");
			String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, map);
			ITextRenderer renderer = new ITextRenderer();
			// 如果内容有中文则需要添加支持中文的字体
			renderer.getFontResolver().addFont("/fonts/calibri.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
			renderer.setDocumentFromString(content);
			renderer.layout();
			renderer.createPDF(os);
			renderer.finishPDF();
		} catch (Exception e) {
			log.error("Fail to generate pdf: {}", e.getMessage(), e);
			return null;
		}

		HttpHeaders respHeaders = new HttpHeaders();
		respHeaders.setContentType(MediaType.APPLICATION_PDF);
		return new ResponseEntity<>(os.toByteArray(), respHeaders, HttpStatus.OK);
	}
}
